/*
 *所有关于Equipmentledger类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*EquipmentledgerService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Linq.Expressions;
using VOL.Core.BaseProvider;
using VOL.Core.Extensions;
using VOL.Core.Extensions.AutofacManager;
using VOL.Core.Utilities;
using VOL.Domain.Dto;
using VOL.Domain.Infrastructure;
using VOL.Domain.IRepositories;
using VOL.Entity.DomainModels;

namespace VOL.Domain.Services
{
    public partial class EquipmentledgerService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IBaseRepository<Equipmentledger> _equipmentledgerbaseRepository;
        private readonly IEquipmentledgerRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public EquipmentledgerService(
            IEquipmentledgerRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IBaseRepository<Equipmentledger> equipmentledgerbaseRepository
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _equipmentledgerbaseRepository = equipmentledgerbaseRepository;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
      


        /// <summary>
        /// 获取设备台账分页数据（使用DTO）
        /// </summary>
        public async Task<PageGridData<Equipmentledger>> GetEquipmentLedgerPage(GetEquipmentledgerDto dto)
        {
            // 验证参数
            if (dto == null)
                dto = new GetEquipmentledgerDto();

            // 构建查询
            var query = _equipmentledgerbaseRepository.GetAll();

            // 条件过滤
            query = query.WhereIF(!string.IsNullOrEmpty(dto.EquipmentCode),
                               x => x.EquipmentCode.Contains(dto.EquipmentCode))
                      .WhereIF(!string.IsNullOrEmpty(dto.EquipmentName),
                               x => x.EquipmentName.Contains(dto.EquipmentName))
                      .WhereIF(dto.DeviceId.HasValue && dto.DeviceId > 0,
                               x => x.DeviceId == dto.DeviceId);

            // 创建返回结果
            var result = new PageGridData<Equipmentledger>();

            // 获取总记录数
            result.total = await query.CountAsync();

            // 默认排序
            query = query.OrderByDescending(x => x.Id);


            // 执行分页
            result.rows = await query
                .Skip((dto.Page - 1) * dto.PageSize)
                .Take(dto.PageSize)
                .ToListAsync();

            return result;
        }

        /// <summary>
        /// 修改设备台账信息
        /// </summary>
        /// <param name="entity">设备台账实体</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> UpdateEquipmentLedger(Equipmentledger entity)
        {
            var result = new WebResponseContent();
            if (entity == null || entity.Id <= 0)
            {
                return result.Error("参数错误");
            }
            var existingEntity =  _equipmentledgerbaseRepository.GetAll().FirstOrDefault(x => x.Id == entity.Id);

            if (existingEntity == null)
            {
                return result.Error("未找到要修改的记录");
            }
            existingEntity.EquipmentCode = entity.EquipmentCode;
            existingEntity.EquipmentName = entity.EquipmentName;
            existingEntity.Brand = entity.Brand;
            existingEntity.SpecificationModel = entity.SpecificationModel;
            existingEntity.AffiliatedWorkshop = entity.AffiliatedWorkshop;
            existingEntity.EquipmentStatus = entity.EquipmentStatus;
            existingEntity.DeviceId = entity.DeviceId;

            try
            {
                await _equipmentledgerbaseRepository.Update(existingEntity);
                return result.OK("修改成功");
            }
            catch (Exception ex)
            {
                return result.Error($"修改失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除设备台账信息
        /// </summary>
        /// <param name="id">设备台账ID</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> DeleteEquipmentLedger(int id)
        {
            var result = new WebResponseContent();

            // 参数验证
            if (id <= 0)
            {
                return result.Error("参数错误");
            }

            // 获取要删除的记录
            var existingEntity =  _equipmentledgerbaseRepository.GetAll().FirstOrDefault(x => x.Id == id);

            if (existingEntity == null)
            {
                return result.Error("未找到要删除的记录");
            }

            try
            {
                // 执行删除操作
                await _equipmentledgerbaseRepository.Delete(existingEntity);
                return result.OK("删除成功");
            }
            catch (Exception ex)
            {
                return result.Error($"删除失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 添加设备台账信息
        /// </summary>
        /// <param name="entity">设备台账实体</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> AddEquipmentLedger(Equipmentledger entity)
        {
            var result = new WebResponseContent();

            // 参数验证
            if (entity == null)
            {
                return result.Error("参数错误");
            }
            
            // 设置创建时间
            entity.CreateTime = DateTime.Now;
            try
            {
                // 执行添加操作
                await _equipmentledgerbaseRepository.Add(entity);

                // 返回成功消息和新增记录的ID
                return result.OK($"添加成功");
            }
            catch (Exception ex)
            {
                return result.Error($"添加失败：{ex.Message}");
            }
        }

    }
}
